package com.fengmoxi.ctv.activity;

import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;

import com.fengmoxi.ctv.databinding.ActivityCameraBinding;
import com.fengmoxi.ctv.manage.HomeButtonReceiver;
import com.herohan.uvcapp.CameraHelper;
import com.herohan.uvcapp.ICameraHelper;
import com.serenegiant.usb.Size;

public class CameraActivity extends AppCompatActivity {

    private static final String TAG = CameraActivity.class.getSimpleName();
    private static final boolean DEBUG = true;
    private ActivityCameraBinding binding;
    private UsbDevice mUsbDevice;
    public static CameraActivity cameraActivity;
    private HomeButtonReceiver mHomeButtonReceiver;
    /**
     * CameraHelper是管理Camera服务的客户端
     * （功能包括：选择设备，打开设备，连接设备，关联预览用的CameraView，拍照，录像，断开连接等操作）
     * 其中通过addSurface，关联预览用的Surface比较关键，分为三种情况：
     * a. 连接设备成功时，执行addSurface
     * b. 旋转屏幕，成功进入OnResume时，CameraView生成Surface，并执行回调onSurfaceCreated方法，在方法中执行addSurface
     */
    private ICameraHelper mCameraHelper;
    private final ICameraHelper.StateCallback mStateCallback = new MyCameraHelperCallback();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCameraBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        cameraActivity = this;
        mHomeButtonReceiver = new HomeButtonReceiver(this, new HomeButtonReceiver.OnHomeBtnPressListener() {
            @Override
            public void onHomeBtnPress() {
                finish();
            }

            @Override
            public void onHomeBtnLongPress() {

            }
        });
        mHomeButtonReceiver.start();
    }

    @Override
    protected void onDestroy() {
        mHomeButtonReceiver.stop();
        clearCameraHelper();
        super.onDestroy();
    }

    @Override
    public void onStart() {
        super.onStart();
        resetCameraHelper();
    }

    private void resetCameraHelper() {
        clearCameraHelper();
        initCameraHelper();
    }

    public void initCameraHelper() {
        mCameraHelper = new CameraHelper();
        mCameraHelper.setStateCallback(mStateCallback);
    }

    /**
     * 程序结束或者UVC设备断开连接时，释放CameraHelper
     */
    private void clearCameraHelper() {
        if (mCameraHelper != null) {
            mCameraHelper.releaseAll();
            mCameraHelper = null;
        }
    }

    private class MyCameraHelperCallback implements ICameraHelper.StateCallback {
        @Override
        public void onAttach(UsbDevice device) {
            if (DEBUG) Log.v(TAG, "onAttach:device=" + device.getDeviceName());
            mCameraHelper.selectDevice(device);
        }

        /**
         * 获取USB设备权限之后，才开始连接USB摄像头
         */
        @Override
        public void onDeviceOpen(UsbDevice device, boolean createNew) {
            if (DEBUG) Log.v(TAG, "onDeviceOpen:device=" + device.getDeviceName());
            if (mCameraHelper != null) {
                mCameraHelper.openCamera();
                binding.tip.setVisibility(View.GONE);
            }
        }

        @Override
        public void onCameraOpen(UsbDevice device) {
            if (DEBUG) Log.v(TAG, "onCameraOpen:");
            mCameraHelper.startPreview();
            // 和摄像头成功建立连接之后，就可以获取摄像头当前预览的实际分辨率
            Size size = mCameraHelper.getPreviewSize();
            if (size != null) {
                // 设置TextureView的宽高比，使之符合摄像头的真实比例
                binding.previewView.setAspectRatio(size.width, size.height);
            }
            if (mCameraHelper != null && binding.previewView.getHolder() != null && binding.previewView.getHolder().getSurface() != null) {
                mCameraHelper.addSurface(binding.previewView.getHolder().getSurface(), false);
            }
//            binding.tip.setVisibility(View.GONE);
        }

        @Override
        public void onCameraClose(UsbDevice device) {
            if (DEBUG) Log.v(TAG, "onCameraClose:");
            if (mCameraHelper != null && binding.previewView.getHolder() != null && binding.previewView.getHolder().getSurface() != null) {
                mCameraHelper.removeSurface(binding.previewView.getHolder().getSurface());
            }
        }

        @Override
        public void onDeviceClose(UsbDevice device) {
            if (DEBUG) Log.v(TAG, "onDeviceClose:");
        }

        @Override
        public void onDetach(UsbDevice device) {
            if (DEBUG) Log.v(TAG, "onDetach:device=" + device.getDeviceName());
            if (device.equals(mUsbDevice)) {
                mUsbDevice = null;
            }
        }

        @Override
        public void onCancel(UsbDevice device) {
            if (DEBUG) Log.v(TAG, "onCancel:device=" + device.getDeviceName());
            if (device.equals(mUsbDevice)) {
                mUsbDevice = null;
            }
        }

//        @Override
//        public void onError(UsbDevice device, CameraException e) {
//            if (DEBUG) Log.v(TAG, "onError:" + e);
//            if (device.equals(mUsbDevice)) {
//                mUsbDevice = null;
//            }
//        }
    }

}